package com.quanquan.user.controller.statisticsReport;

import base.BaseController;
import com.quanquan.user.configBeans.TimeTransformation;
import com.quanquan.user.entity.User;
import com.quanquan.user.request.StatisticsReportRequestBody;
import com.quanquan.user.service.statisticsReport.UserStatisticsReportService;
import enums.ResCodeEnum;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import utils.CalendarUtil;
import utils.DateUtils;
import utils.StringUtil;
import web.response.ResultBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 功能描述:会员模块所有报表
 *
 * @ClassName: UserStatisticsReportController
 * @Author: xiaoqianh丶
 * @Date: 2019-05-27 17:01
 * @Version: V1.0
 */
@RestController
@RequestMapping("/statistical_user")
public class UserStatisticsReportController extends BaseController {


    public static final String DAILY = "daily";
    public static final String WEEK = "week";
    public static final String MONTH = "month";
    public static final String YEAR = "year";
    private final UserStatisticsReportService userStatisticsReportService;

    public UserStatisticsReportController(UserStatisticsReportService userStatisticsReportService) {
        this.userStatisticsReportService = userStatisticsReportService;
    }

    /**
     * 用户每日新增,用户每周新增,用户每月新增
     *
     * @return
     */
    @PostMapping("/user_new")
    public ResultBody userDailyNew(@RequestBody StatisticsReportRequestBody requestBody) {
        String statisticalCycle = requestBody.getStatisticalCycle();
        Date startTime = null;
        Date endTime = null;
        Map<String, Date> map = new HashMap<>();
        if (StringUtil.isNotEmpty(statisticalCycle)) {
            switch (statisticalCycle) {
                case DAILY:
                    //近7天的当前时间
                    String afterDayDate = CalendarUtil.getAfterDayDate("-6");
                    //7天前的当天开始时间和结束时间
                    Map<String, Date> before = CalendarUtil.setDayRange(afterDayDate);
                    //当前时间的开始结束时间
                    Map<String, Date> after = CalendarUtil.setDayRange(map);
                    //真正的时间段
                    startTime = before.get("startTime");
                    endTime = after.get("stopTime");
                    break;
                case WEEK:
                    //当前时间的本周开始时间和结束时间
                    Map<String, Date> afterWeek = CalendarUtil.setWeekRange(map);
                    //本周开始时间 往前6周 前42天（近7周的开始时间）
                    Date countTime = afterWeek.get("startTime");
                    //近7周的开始时间
                    startTime = CalendarUtil.getAfterDayDate("-42", countTime);
                    endTime = afterWeek.get("stopTime");
                    break;
                case MONTH:
                    //当前时间的本月开始时间和结束时间
                    Map<String, Date> afterMonthDate = CalendarUtil.setMonthRange(map);
                    //本月开始时间 往前6月
                    Date countTime2 = afterMonthDate.get("startTime");
                    //前第6个月的开始时间
                    startTime = CalendarUtil.getAfterMonthDate("-6", countTime2);
                    endTime = afterMonthDate.get("stopTime");
                    break;
                case YEAR:
                    Map<String, Date> yearTime = CalendarUtil.setYearRange(map);
                    startTime = yearTime.get("startTime");
                    endTime = yearTime.get("stopTime");
                    break;
                default:
                    throw new IllegalStateException("Unexpected value（参数错误）: " + statisticalCycle);
            }
        }

        List<User> users = userStatisticsReportService.statisticalReports(startTime, endTime);

        Stream<User> userStream = null;
        Map<String, Long> result = new HashMap<>();
        Map<String, Long> stringLongMap = new HashMap<>();
        //计算结果
        // （每日 按上午下午划分）
        if (DAILY.equals(statisticalCycle)) {
            users.parallelStream().forEach(f -> f.setCreateTime(handleTime(f.getCreateTime())));

            result = users.parallelStream().map(User::getCreateTime).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
            stringLongMap = TimeTransformation.formatDay(result);

        }
        // （每周按星期划分）
        if (WEEK.equals(statisticalCycle)) {
            users.parallelStream().forEach(f -> f.setCreateTime(handleTimeWeek(f.getCreateTime())));

            result = users.parallelStream().map(User::getCreateTime).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
            stringLongMap = TimeTransformation.formatWeek(result);

        }
        // （每月按每周划分）
        if (MONTH.equals(statisticalCycle)) {
            users.parallelStream().forEach(f -> f.setCreateTime(handleTimeMonth(f.getCreateTime())));

            result = users.parallelStream().map(User::getCreateTime).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
            stringLongMap = TimeTransformation.formatMonth(result);

        }

        //  (每年按每月划分)

        if(YEAR.equals(statisticalCycle)){
            String s = DateUtils.currentDate();
            String time = s.substring(0,4);
            Map yearMap = new HashMap();
            yearMap.put(time, users.size());
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), yearMap);
        }
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), stringLongMap);

    }

    public static String handleTime(String createTime) {
        //将时间段进行截取
        return createTime.substring(0, 10);
    }

    public static String handleTimeWeek(String createTime) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(createTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(date);
        int week = calendar.get(Calendar.WEEK_OF_YEAR);
        int year = calendar.get(Calendar.YEAR);
        if (week < calendar.get(Calendar.WEEK_OF_YEAR)) {
            year += 1;
        }
        String time = null;
        if (week < 10) {
            time = year + "-0" + week;
        } else {
            time = year + "-" + week;
        }
        return String.valueOf(time);
    }

    public static String handleTimeMonth(String createTime) {
        //将时间段进行截取
        String subTime = createTime.substring(0, 7);
        return subTime;
    }
}
